package com.eschool.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eschool.mapper.ClassRoomMapper;
import com.eschool.mapper.ClassRoomOccupyMapper;
import com.eschool.pojo.ClassRoomDAO;
import com.eschool.pojo.FindRoomDTO;
import com.eschool.service.RoomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoomServiceImpl implements RoomService {
    @Autowired
    ClassRoomMapper classRoomMapper;
    @Autowired
    ClassRoomOccupyMapper classRoomOccupyMapper;


    @Override
    public List<ClassRoomDAO> FindRoom(FindRoomDTO findRoomDTO) {
        QueryWrapper<ClassRoomDAO> queryWrapper = new QueryWrapper<>();
        if (findRoomDTO.getScale() != 0) {
            queryWrapper.eq("scale", findRoomDTO.getScale());
        }
        if (findRoomDTO.getComputer()==1) {
            queryWrapper.eq("computer", 1);
        }
        if (findRoomDTO.getAircon() == 1) {
            queryWrapper.eq("aircon", 1);
        }

        // 2. 添加时间冲突排除条件（跨表子查询）
        if (findRoomDTO.getWeekday() != 0
                && findRoomDTO.getStartTime()!= 0
                && findRoomDTO.getEndTime() != 0) {

            // 子查询逻辑：检查是否存在冲突的占用记录
            queryWrapper.notExists(
                    "SELECT roomid FROM classroom_occupy co " +
                            "WHERE co.roomid = classroom.roomid " +
                            "AND co.weekday = {0} " +
                            "AND (" +
                            "   (co.startTime <= {1} AND co.endTime >= {2}) " + // 时间重叠
                            "   OR " +
                            "   (co.startTime >= {2} AND co.endTime <= {1}) " +  // 完全包含
                            ")",
                    findRoomDTO.getWeekday(),
                    findRoomDTO.getEndTime(),
                    findRoomDTO.getStartTime()

            );
        }

        if(findRoomDTO.getBuilding() != null){
            queryWrapper.like("room",findRoomDTO.getBuilding());
        }

        queryWrapper.orderByAsc("room");
        // 3. 单次查询直接返回最终结果
        return classRoomMapper.selectList(queryWrapper);

    }
}
